//index.js
//获取应用实例
var app = getApp();
var goodslist = [];
var goods_spec = {};
Page({
  data: {
    shop_list_select: [],
    shoppingCartList: [],
    goods: [],
    tabid: 0,
    popup: 0,
    popup2: 0,
    data: {},
    choose_property_data: {},
    choose_spec: {},
    disabled: 0,
    spec_keys_str: '',
    config: {},
    tableInfo:{},
    table_id:0,
  },
  btn_cancel: function () {
    this.setData({ popup: 0 });
  },
  show_popup: function () {
    this.setData({ popup: 1 });
  },
  
  onLoad: function (options) {
    // wx.navigateTo({
    //   url: "/bookOffline/pages/order"
    // });
    // console.log( );
    var extConfigSync = app.getExtConfigSync();
    var that = this;
    this.data.table_id = options.table_id ? options.table_id : 92;
    if (options.scene) {
      this.data.table_id = decodeURIComponent(options.scene);
    }
  
    this.setData({ theme: extConfigSync.theme})
    app.getUserInfo(function (userInfo) {
      that.getTableInfo();
    })
    
  },
  //桌位信息
  getTableInfo: function () {
    app.api("mall/mall_tables/find", {
      id: this.data.table_id
    }, (res) => {
      if (res.code != 200) {
        app.alert(res.msg);
      }
     
      this.setData({ tableInfo: res.data, shop_info: res.data.shop });
      this.getPageConfig();
      this.getcartByUserId();
    })
  },

  //页面配置
  getPageConfig: function () {
    app.api("mall/pages/getPageConfig", {
      page: "bookOffline/index/index",
      shop_id: this.data.shop_info.id
    }, (res) => {
      if (res.code != 200) {
        app.alert(res.msg);
      }
      this.setData({ config: res.data });
      this.loadList();
    })
  },
  /**
 * 页面相关事件处理函数--监听用户下拉动作
 */
  onPullDownRefresh: function () {
    this.getPageConfig();
    wx.stopPullDownRefresh();
    this.getcartByUserId();
  },
  //商品列表
  loadList: function () {
    var that = this;
    var config = this.data.config;
    if (!config.attrs) {
      that.setData({
        goods: []
      });
      return;
    }
    for (let i in config.attrs) {
      var params = config.attrs[i].params;
      app.api("mall/goods/get", params, (res) => {
        if (res.code != 200) {
          app.alert(res.msg);
        }

        if (res.data && res.data.list) {
          goodslist[i] = res.data.list;
        } else {
          goodslist[i] = [];
        }
        var goods = []
        for (var k in goodslist[i]) {
          var item = goodslist[i][k];
          goods.push({
            default_img: item['default_img'],
            goods_name: item['goods_name'],
            origin_price: item['origin_price'],
            price: item['price'],
            total_stock: item['total_stock'],
            sub_title: item['sub_title'],
          })
        }
        that.data.goods[i] = goods;
        that.setData({
          goods: that.data.goods
        });

      })
    }


  },
  showTabs: function (e) {
    wx.showLoading();
    var id = e.currentTarget.dataset.id;
    if (this.data.tabid == id) {
      return;
    }
    this.setData({ tabid: id });
    wx.hideLoading();
  },
  // 购物车
  getcartByUserId: function () {
    var that = this;
    app.api("mall/cart/getcartByUserId", { 
      shop_id: this.data.shop_info.id,
      table_id: this.data.table_id
      }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
      } else if (res.data) {
        that.setData({ shoppingCartList: res.data });
        console.log("shoppingCartList", that.data.shoppingCartList);
      }
    })
  },
  //商品数量减
  minus: function (e) {
    var id = e.currentTarget.dataset.id;
    var shoppingCartList = this.data.shoppingCartList;
    if (shoppingCartList.list[id].count < 1) {
      shoppingCartList.list[id].count = 0;
    } else {
      shoppingCartList.list[id].count--;
    }
    this.setData({ shoppingCartList: shoppingCartList });
    this.addToCart({
      count: shoppingCartList.list[id].count,
      goods_spec_id: e.currentTarget.dataset.goods_spec_id,//  $(input).attr("goods_spec_id"),
      goods_id: e.currentTarget.dataset.goods_id,
    })

  },
  //商品数量加
  plus: function (e) {
    var id = e.currentTarget.dataset.id;
    var shoppingCartList = this.data.shoppingCartList;
    shoppingCartList.list[id].count++;
    this.setData({ shoppingCartList: shoppingCartList });
    this.addToCart({
      count: shoppingCartList.list[id].count,
      goods_spec_id: e.currentTarget.dataset.goods_spec_id,//  $(input).attr("goods_spec_id"),
      goods_id: e.currentTarget.dataset.goods_id,
    })
  },
  //商品数量
  changeCount: function (e) {
    var id = e.currentTarget.dataset.id;
    var count = e.detail.value;
    var shoppingCartList = this.data.shoppingCartList;
    shoppingCartList.list[id].count = count;
    this.setData({ shoppingCartList: shoppingCartList });
    this.addToCart({
      count: count,
      goods_spec_id: e.currentTarget.dataset.goods_spec_id,//  $(input).attr("goods_spec_id"),
      goods_id: e.currentTarget.dataset.goods_id,
    })

  },
  //加入购物车
  addToCart: function (post, callback) {
    wx.showLoading();
    var that = this;
    post.table_id = this.data.table_id;
    app.api("/mall/cart/add", post, function (res) {
      wx.hideLoading();
      if (res.code != 200) {
        app.alert(res.msg);
      } else {
        callback ? callback(res) : '';
        that.setData({ shoppingCartList: res.data });
        if (res.data.count == 0) {
          that.btn_cancel();
        }
      }
    })
  },
  //清空购物车
  clearCart: function () {
    wx.showLoading();
    var that = this;
    app.api("mall/cart/clearCart", { shop_id: this.data.shop_info.id, table_id: this.data.table_id }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
      } else {
        //phpkitApp.alert("恭喜,成功清空购物车!");
        wx.showToast({
          title: "恭喜,成功清空购物车!",
          icon: 'success'
        });
        that.setData({ shoppingCartList: {} });
        that.btn_cancel();
      }
      wx.hideLoading();
    })
  },
  //去结算
  settle_accounts: function (e) {
    var formId = e.detail.formId;
    app.api("api/index/index", { formId: formId});
    wx.navigateTo({
      url: "/bookOffline/pages/checkout?table_id=" + this.data.table_id
    });
   
  },
  //选规格

  buyNow: function (e) {
    var postData = {};
    var item_id = e.currentTarget.dataset.item_id;
    var tab_id = e.currentTarget.dataset.tab_id;
    if (tab_id > -1 && item_id > -1) {
      var data = goodslist[tab_id][item_id];
      goods_spec = data.goods_spec;
      data.goods_spec = {};
    } else if (this.data.data.id) {
      var data = this.data.data;
    } else {
      app.alert("请选择商品");
      return;
    }


    console.log(data);
    if (data.property_arr.length > 0 && this.data.choose_spec.spec_stock > 0) {
      postData.goods_id = this.data.choose_spec.goods_id;
      postData.goods_spec_id = this.data.choose_spec.id;
      //可以去结算
    } else if (data.property_arr.length == 0) {
      postData.goods_id = data.id;
    } else if (this.data.popup2 == 1) {
      wx.showToast({
        title: '请选择商品规格',
        image: '/image/info.png'
      });
      return;
    } else {
      this.setData({ data: data });
      this.chooseSpec();
      return;
    }
    //加入购车
    this.addToCart(postData, () => {
      wx.showToast({
        title: "成功加入购物车!",
        icon: 'success'
      });
    });
    this.hide_choose_goods();
  },
  hide_choose_goods: function () {
    goods_spec = {};
    this.setData({ popup2: 0, data: {}, choose_spec: {}, choose_property_data: {} });
  },
  //弹出选规格
  chooseSpec: function () {
    this.setData({ popup2: 1 });
  },
  //选规格
  chooseProperty: function (e) {
    //console.log(e); 
    var property = e.currentTarget.dataset.property;
    var subProperty = e.currentTarget.dataset.subProperty;
    var choose_property_data = this.data.choose_property_data;
    choose_property_data[property] = subProperty;
    this.setData({ choose_property_data: choose_property_data });
    var arr = []
    for (var i in choose_property_data) {
      arr.push(choose_property_data[i]);
    }

    if (arr.length == this.data.data.property_arr.length) {
      this.setData({ spec_keys_str: arr.join(" ") });
      var l = arr.length;
      for (var j = 0; j < (5 - l); j++) {
        arr.push("");
      }
      // console.log(arr,arr);
      var spec_keys = arr.sort();
      var spec_keys_str = spec_keys.join("_");
      if (goods_spec[spec_keys_str] && goods_spec[spec_keys_str].spec_stock > 0) {
        this.setData({ choose_spec: goods_spec[spec_keys_str] });
        this.setData({ disabled: 0 });
      } else {
        wx.showToast({
          title: '已售空',
          image: '/image/info.png'
        });
        this.setData({ disabled: 1 });
      }
    }

    // console.log(this.data.choose_spec);
    //choose_spec
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // app.setPageData("bookOffline/pages/index", { reload: 1 });
    var reload = app.getPageData("bookOffline/pages/index");
    if (reload == 1) {
      this.getcartByUserId();
      app.setPageData("bookOffline/pages/index", { reload: 0 });
    }

  },


})
